/**
 * 基础控制器抽象类
 * 职责：
 * 1. 定义Controller层统一接口
 * 2. 协调多个Service
 * 3. 处理业务流程编排
 * 4. 管理事务和错误处理
 */
export abstract class BaseController {
    protected readonly controllerName: string;
    protected isInitialized: boolean = false;

    constructor() {
        this.controllerName = this.constructor.name;
    }

    /**
     * 控制器初始化
     */
    async init(): Promise<void> {
        if (this.isInitialized) {
            console.warn(`Controller ${this.controllerName} already initialized`);
            return;
        }
        
        console.log(`Initializing controller: ${this.controllerName}`);
        await this.onInit();
        this.isInitialized = true;
        console.log(`Controller ${this.controllerName} initialized successfully`);
    }

    /**
     * 控制器销毁
     */
    async destroy(): Promise<void> {
        if (!this.isInitialized) {
            console.warn(`Controller ${this.controllerName} not initialized`);
            return;
        }
        
        console.log(`Destroying controller: ${this.controllerName}`);
        await this.onDestroy();
        this.isInitialized = false;
        console.log(`Controller ${this.controllerName} destroyed successfully`);
    }

    /**
     * 检查控制器是否已初始化
     */
    protected ensureInitialized(): void {
        if (!this.isInitialized) {
            throw new Error(`Controller ${this.controllerName} not initialized. Call init() first.`);
        }
    }

    /**
     * 子类重写此方法实现特定初始化逻辑
     */
    protected async onInit(): Promise<void> {
        // 默认空实现
    }

    /**
     * 子类重写此方法实现特定销毁逻辑
     */
    protected async onDestroy(): Promise<void> {
        // 默认空实现
    }

    /**
     * 获取控制器名称
     */
    getControllerName(): string {
        return this.controllerName;
    }

    /**
     * 检查控制器状态
     */
    isReady(): boolean {
        return this.isInitialized;
    }

    /**
     * 日志记录方法
     */
    protected log(message: string, level: 'info' | 'warn' | 'error' = 'info'): void {
        const timestamp = new Date().toISOString();
        const logMessage = `[${timestamp}] [${this.controllerName}] ${message}`;
        
        switch (level) {
            case 'info':
                console.log(logMessage);
                break;
            case 'warn':
                console.warn(logMessage);
                break;
            case 'error':
                console.error(logMessage);
                break;
        }
    }

    /**
     * 执行业务操作的包装方法，统一错误处理
     */
    protected async executeOperation<T>(
        operation: () => Promise<T>,
        operationName: string
    ): Promise<T> {
        this.ensureInitialized();
        
        try {
            this.log(`Starting operation: ${operationName}`);
            const result = await operation();
            this.log(`Operation completed successfully: ${operationName}`);
            return result;
        } catch (error) {
            this.log(`Operation failed: ${operationName}, Error: ${(error as any).message}`, 'error');
            throw error;
        }
    }

    /**
     * 并行执行多个操作
     */
    protected async executeParallel<T>(
        operations: Array<() => Promise<T>>,
        operationName: string
    ): Promise<T[]> {
        this.ensureInitialized();
        
        try {
            this.log(`Starting parallel operations: ${operationName}`);
            const results = await Promise.all(operations.map(op => op()));
            this.log(`Parallel operations completed successfully: ${operationName}`);
            return results;
        } catch (error) {
            this.log(`Parallel operations failed: ${operationName}, Error: ${(error as any).message}`, 'error');
            throw error;
        }
    }
}
